package com.lagou.controller;

import com.lagou.service.IAuthCodeService;
import com.lagou.service.IEmailServiceClient;
import com.lagou.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/code")
public class AuthCodeController {

    @Autowired
    private IAuthCodeService authCodeService;

    @Autowired
    private IEmailServiceClient emailServiceClient;

    @Value("${config.code.length}")
    private int codeLength;

    @GetMapping("/create/{email}")
    public boolean createAuthCode(@PathVariable("email") String email) {
        String code = RandomUtil.getCode(codeLength);
        authCodeService.createNewCode(email, code);
        return emailServiceClient.sendMail(email, code);
    }

    @GetMapping("/validate/{email}/{code}")
    public int validateAuthCode(@PathVariable("email") String email, @PathVariable("code") String code) {
        return authCodeService.validateAuthCode(email, code).ordinal();
    }
}
